var myPlugin = requirePlugin('WechatSI');
const $websocketUrl = require('./utils/request').websocketUrl;
App({
  onShow() {
    this.globalData.socketClientTimer = setInterval(() => {
      // this.checkLoginUserSocket();
      if (wx.getStorageSync('token') != '') {
        this.connectSocket();
        clearInterval(this.globalData.socketClientTimer)
      }
    }, 5000)


  },



  checkLoginUserSocket: function () {
    if (wx.getStorageSync('token') != '') {
      this.connectSocket();
      clearInterval(this.globalData.socketHeartTimer)
    } else {
      this.closeSocketFunction()
    }

  },



  connectSocket(e) {

    var that = this
    wx.connectSocket({ 
      url: `wss://${$websocketUrl}/zlWebsocket/imserver/${wx.getStorageSync('gongHao')}`,
      success: (res => {
        that.globalData.isSocketConnect = true
        // 初始化连接监听
        that.initEventHandler()
      }),
      fail: (fail => {
        console.log(fail);
      })
    })
  },

  initEventHandler() {
    var that = this
    // socket连接开启
    wx.onSocketOpen((result) => {
      // 开启心跳
      that.startHeart()
    })
    // socket连接关闭
    wx.onSocketClose((res) => {
      if (that.globalData.isSocketConnect) {
        that.connectSocket()
      }
    })
    // 接收socket消息
    wx.onSocketMessage((res) => {
      console.log("onSocketMessage")
      console.log(res)
      this.innerAudioContext = wx.createInnerAudioContext();
      let that = this
      myPlugin.textToSpeech({
        lang: 'zh_CN',
        content: res.data,
        success: function (res) {
          that.playAudio(res.filename);
        },
      })

    })
  },




  startHeart: function () {
    if (this.globalData.isSocketConnect) {
      this.globalData.socketHeartTimer = setInterval(() => {
        var msg = JSON.stringify({
          'data': 'ping'
        })
        wx.sendSocketMessage({
          data: msg,
          success: function (res) { },
          fail: function (res) { }
        })
      }, 60000)
    } else {
      clearTimeout(this.globalData.socketHeartTimer)
    }
  },

  //此页面关闭socket和定时器的函数
  closeSocketFunction: function () {
    if (this.globalData.isSocketConnect) {
      // 标识socket已断开
      this.globalData.isSocketConnect = false
      // 关闭socket连接
      wx.closeSocket()
      // 关闭socket心跳定时器
      clearInterval(this.globalData.socketHeartTimer)
    }

  },


  playAudio(e) {
    this.innerAudioContext.src = e
    this.innerAudioContext.play();
  },
  globalData: {
    userInfo: null,
    //当前socket是否连接
    isSocketConnect: false,
    socketHeartTimer: null,
  },


  onHide: function () {
    console.log('=========>');

    clearInterval(this.globalData.socketClientTimer)
    // 关闭socket
    this.closeSocketFunction()
  },
})

//
